package wci.frontend.pascal.parsers;

import static wci.frontend.pascal.PascalErrorCode.INCOMPATIBLE_TYPES;
import static wci.frontend.pascal.PascalErrorCode.MISSING_UNTIL;
import static wci.frontend.pascal.PascalTokenType.UNTIL;
import static wci.intermediate.icodeimpl.ICodeNodeTypeImpl.LOOP;
import static wci.intermediate.icodeimpl.ICodeNodeTypeImpl.TEST;
import wci.frontend.Token;
import wci.frontend.pascal.PascalParserTD;
import wci.intermediate.ICodeFactory;
import wci.intermediate.ICodeNode;
import wci.intermediate.TypeSpec;
import wci.intermediate.symtabimpl.Predefined;
import wci.intermediate.typeimpl.TypeChecker;

/**
 * <h1>RepeatStatementParser</h1>
 *
 * <p>解析Pascal REPEAT语句</p>
 *
 * <p>Copyright (c) 2009 by Ronald Mak</p>
 * <p>For instructional purposes only.  No warranties.</p>
 */
public class RepeatStatementParser extends StatementParser
{
    public RepeatStatementParser(PascalParserTD parent)
    {
        super(parent);
    }

    public ICodeNode parse(Token token)
        throws Exception
    {
    	//吞噬掉语句开始的REPEAT
        token = nextToken();  

        ICodeNode loopNode = ICodeFactory.createICodeNode(LOOP);
        ICodeNode testNode = ICodeFactory.createICodeNode(TEST);

        //解析包含在REPEAT和UNTIL中间的语句列表
        StatementParser statementParser = new StatementParser(this);
        statementParser.parseList(token, loopNode, UNTIL, MISSING_UNTIL);
        token = currentToken();

        //最后的测试表达式
        ExpressionParser expressionParser = new ExpressionParser(this);
        ICodeNode exprNode = expressionParser.parse(token);
		testNode.addChild(exprNode);
        loopNode.addChild(testNode);//最后一个子节点
        
        TypeSpec exprType = exprNode != null ? exprNode.getTypeSpec()
                : Predefined.undefinedType;
		if (!TypeChecker.isBoolean(exprType)) {
			errorHandler.flag(token, INCOMPATIBLE_TYPES, this);
		}
        return loopNode;
    }
}
